package com.mycontact.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.mycontact.client.ClientFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Button;
import com.mycontact.client.place.ViewContactsPlace;
import com.mycontact.shared.ContactProxy;
import com.mycontact.shared.ContactRequest;

public class EditContactMainPanel extends Composite {
	private static EditContactMainPanelUiBinder uiBinder = GWT.create(EditContactMainPanelUiBinder.class);
	@UiField TextBox txtName;
	@UiField TextBox txtAddress;
	@UiField Button butSave;
	private ClientFactory clientFactory;
	private ContactProxy contact;

	interface EditContactMainPanelUiBinder extends UiBinder<Widget, EditContactMainPanel> { }

	public EditContactMainPanel() {
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	@UiHandler("butSave")
	void onClickSave(ClickEvent e)
	{
		ContactRequest request = clientFactory.getRequestFactory().contactRequest();
		
		// Create editable contact
		ContactProxy editableContact = request.edit(contact);
		
		// Save contact
		editableContact.setName(txtName.getText());
		editableContact.setAddress(txtAddress.getText());
		request.persist().using(editableContact);
		request.fire(
				new Receiver<Void>() {
					@Override
					public void onSuccess(Void response) {
						// Move to ViewContactsPlace
						clientFactory.getPlaceController().goTo(new ViewContactsPlace());
					}
				}
		);
	}
	
	public void getContact(String contactId) {
		if(clientFactory != null) {
			clientFactory.getRequestFactory().contactRequest().findContact(Long.parseLong(contactId)).fire(
					new Receiver<ContactProxy>() {
						@Override
						public void onSuccess(ContactProxy response) {
							contact = response;
							
							// Set to textboxes
							txtName.setText(contact.getName());
							txtAddress.setText(contact.getAddress());
						}
					}
			);
		}
	}
	
	public void setClientFactory(ClientFactory cf) {
		clientFactory = cf;
	}
}
